﻿var dataService = require('../service/dataService');
var signatureConfig = require('../../config/wxSignature');
var logger = require('../../utils/logHelper').helper;
var request = require('request');
// var schedule = require('node-schedule');
var async=require('async');
var wxtemplate=require('../../config/wx-template');

// new签证
exports.getSignature = function (req, res) {
    dataService.getSignature(function (err, doc) {
        if (err) {
            console.log(err);
            res.send({
                msg: err.message,
                success: false
            })
        } else {
            res.send({
                success: true,
                getSign: doc
            })
        }
    })
}

// token生成
exports.getToken = function (req, res) {
    var url = decodeURIComponent(req.query.url);
    var spotid = req.query.spotid;
    dataService.getToken(spotid, url, function (err, doc) {
        if (err) {
            console.log(err);
            res.send({
                success: false,
                msg: err.message
            })
        } else {
            res.send({
                success: true,
                getSign: doc
            })
        }
    })
}

exports.downloadWXImage = function (req, res) {
    console.log(req.body)
    var images = req.body.images;
    var businessid = req.body.businessid;
    var spotid=req.body.spotid;
    dataService.downloadWXImage(businessid, images, spotid,function (err, data) {
        if (err) {
            logger.writeLogError(err);
            res.send({
                msg: err.message,
                success: false
            })
        } else {
            res.send({
                success: true,
                data: data
            })
        }
    });
}

exports.base64 = function (req, res) {
    var base64Data = req.body.base64;
    //console.log(req.body);
    base64Data = base64Data.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = new Buffer(base64Data, 'base64');
    dataService.base64(dataBuffer, function (err, data) {
        if (err) {
            logger.writeLogError(err);
            console.log(err);
            return res.send({
                success: 0,
                msg: '出错啦...'
            })
        } else {
            res.send({
                success: 1,
                data: data
            })
        }
    })
};

/**
 * 向用户发送消息
 * @param  {[type]} userid [description]
 * @param  {[type]} msg    [description]
 * @return {[type]}        [description]
 */
exports.sendMsgToUser = function (userid, msg) {
    //console.log(userid,msg)
    //根据用户编号查询uninid,再用uninid去查询微信用户列表
    //console.log(userid);
    dataService.findUserGZHOpenid(userid, function (err, openids) {
        //console.log(err)
        if (openids == -1) {
            //console.log("未查询到用户，请确认关注");
        } else {
            var loop = 0;
            async.whilst(
                function () {
                    return loop < openids.length;
                },
                function (wcb) {
                    //for (var i = 0; i < openids.length; i++) {
                        var openid = openids[loop].openid;
                        dataService.getTokenbyappidsetOpenid(openids[loop].appid,openid,function (err, doc) {
                            if (err) {
                                logger.writeLogError(err);
                                console.log(err);
                            } else {
                                var url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + doc.token;
                                var option;
                                switch (msg.type) {
                                    case 'text'://文字消息
                                        option = {
                                            body: "{\"touser\": \"" + doc.openid + "\", \"msgtype\": \"text\", \"text\": {\"content\": \"" + msg.content + "\"}}"
                                        };
                                        break;
                                    //case "image"://图片消息
                                    //	option = {
                                    //		body:'{"touser": "'+openid+'", "msgtype": "image", "text": {"content": "'+msg+'"}}'
                                    //	};
                                    //	break;
                                    case 'news'://可以是多条图文消息,暂时固定为一条，todo
                                        option = {
                                            body: '{"touser": "' + doc.openid + '", "msgtype": "news", "news": {"articles":[{"title":"' + msg.title + '","description":"' + msg.description + '","url":"' + msg.url + '","picurl":"' + msg.picurl + '"}]}}'
                                        };
                                        break;
                                }
                                request.post(url, option, function (error, response, body) {
                                    loop++;
                                    wcb(err);
                                })
                            }
                        })
                    //}
                },
                function (err) {
                    //cb(err, {
                    //    count: openids.length,
                    //    success: loop
                    //})
                }
            )
        }

    })
}

/**
 * 发送模板消息
 * @param userid
 * @param msg
 */
exports.sendModeMsgToUser = function (userid, msg) {
    //根据用户编号查询uninid,再用uninid去查询微信用户列表
    //console.log(userid);
    dataService.findUserGZHOpenid(userid, function (err, openids) {
        //console.log(err)
        if (openids == -1) {
            console.log("未查询到用户，请确认关注");
        } else {
            var loop = 0;
            async.whilst(
                function () {
                    return loop < openids.length;
                },
                function (wcb) {
                    //for (var i = 0; i < openids.length; i++) {
                        var openid = openids[loop].openid;
                        dataService.getTokenbyappidsetOpenid(openids[loop].appid,openid,function (err, doc) {
                            if (err) {
                                logger.writeLogError(err);
                                console.log(err);
                            } else {
                                var url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + doc.token;
                                var option;
                                switch (msg.type) {
                                    case 'paymoney'://文字消息
                                        option = {
                                            body: '{"touser": "' + doc.openid + '","template_id":"'+wxtemplate[doc.appid][0]+'","topcolor":"#FF0000","data":{"first":{"value":"' + msg.title + '","color":"#173177"},"keyword1":{"value":"' + msg.keyword1 + '","color":"#173177"},"keyword2":{"value":"' + msg.keyword2 + '","color":"#173177"},"keyword3":{"value":"' + msg.keyword3 + '","color":"#173177"},"keyword4":{"value":"' + msg.keyword4 + '","color":"#173177"},"keyword5":{"value":"' + msg.keyword5 + '","color":"#173177"},"remark":{"value":"' + msg.remark + '","color":"#173177"}}}'
                                        };
                                        break;
                                    case 'acceptmoney':
                                        option = {
                                            body: '{"touser": "' + doc.openid + '","template_id":"'+wxtemplate[doc.appid][1]+'","topcolor":"#FF0000","data":{"first":{"value":"' + msg.title + '","color":"#173177"},"keyword1":{"value":"' + msg.keyword1 + '","color":"#173177"},"keyword2":{"value":"' + msg.keyword2 + '","color":"#173177"},"keyword3":{"value":"' + msg.keyword3 + '","color":"#173177"},"remark":{"value":"' + msg.remark + '","color":"#173177"}}}'
                                        };
                                        break;
                                    case 'refundmoney':
                                        option = {
                                            body: '{"touser": "' + doc.openid + '","template_id":"'+wxtemplate[doc.appid][2]+'","topcolor":"#FF0000","data":{"first":{"value":"' + msg.title + '","color":"#173177"},"keyword1":{"value":"' + msg.keyword1 + '","color":"#173177"},"keyword2":{"value":"' + msg.keyword2 + '","color":"#173177"},"keyword3":{"value":"' + msg.keyword3 + '","color":"#173177"},"remark":{"value":"' + msg.remark + '","color":"#173177"}}}'
                                        };
                                        break;
                                    case 'refundmsg':
                                        option = {
                                            body: '{"touser": "' + doc.openid + '","template_id":"'+wxtemplate[doc.appid][3]+'","topcolor":"#FF0000","url":"' + msg.url + '","data":{"first":{"value":"' + msg.title + '","color":"#173177"},"keyword1":{"value":"' + msg.keyword1 + '","color":"#173177"},"keyword2":{"value":"' + msg.keyword2 + '","color":"#173177"},"remark":{"value":"' + msg.remark + '","color":"#173177"}}}'
                                        };
                                        break;
                                    case 'event':
                                        option = {
                                            body: '{"touser": "' + doc.openid + '","template_id":"307k82WllUMIlXLYuNDVkGk4RdRv-Hj-BHIITBzmlzU","topcolor":"#FF0000","url":"' + msg.url + '","data":{"first":{"value":"' + msg.title + '","color":"#173177"},"keyword1":{"value":"' + msg.keyword1 + '","color":"#173177"},"keyword2":{"value":"' + msg.keyword2 + '","color":"#173177"},"remark":{"value":"' + msg.remark + '","color":"#173177"}}}'
                                        };
                                        break;
                                }
                                request.post(url, option, function (error, response, body) {
                                    // console.log(error, response, body);
                                    loop++;
                                    wcb(err);
                                })
                            }
                        })
                    //}
                },
                function (err) {
                    //cb(err, {
                    //    count: openids.length,
                    //    success: loop
                    //})
                }
            )
        }
    })
}

exports.getTicket = function (req, res) {

    var url = req.query.url;
    var spotid = req.query.spotid;
    //console.log("进入获取签证"+spotid)
    dataService.getTicket(url, spotid, function (err, data) {
        if (err) {
            console.log(err.message);
            logger.writeLogError(err);
            res.send({
                success: 0,
                msg: '获取微信票据出错啦'
            })
        } else {
            res.send({
                success: 1,
                sign: data
            })
        }
    })
}
